package com.cci.kangdao.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.CompanyTDao;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.cci.kangdao.dao.CourseTrainingDao;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CourseTrainingService;
import com.cci.kangdao.service.PropertiesUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
/**
 * @Description: 课程培训相关业务
 * @Company: CTY
 * @author myc
 * @date 2018-02-27
 * @version 1.0
 */
@Service("courseTrainingService")
public class CourseTrainingServiceImpl implements CourseTrainingService {
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Resource
	private CourseTrainingDao courseTrainingDao;
	@Resource
	private PropertiesUtils propertiesUtils;
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Resource
	private CompanyTDao companyTDao;

	/**
	 * App获取本人课程接口
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getMyCourseTraining(Map map) {
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询type:课程类型，0选修，1必须，2所有
			 */
			String type = ""+map.get("type");
			if(map.get("type") == null  || map.get("type").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = 5;
			if (map.get("pagesize") != null && !map.get("pagesize").toString().equals("")) {
				pagesize = Integer.parseInt(map.get("pagesize").toString());
			}

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
//			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			UserT userT = UserThreadLocal.get();
			map.put("userId", userT.getId());
			map.put("dealerLevel", userT.getDealerLevel() + "");
			/**
			 * 1、康明斯、客户查询所有的课件 +级别
			 * 2、jv查询自己创建的课件 +级别
			 * 3、dealer则查询企业授权服务站的课件 + 级别
			 *
			 */
			if(userT.getIsType() ==0 || userT.getIsType() ==1){  //康明斯和客户
				map.put("userType", 0);
			}else if(userT.getIsType() ==6){ //dealer用户组
				map.put("userType", 6);
				map.put("serviceStationID", ""+userT.getServiceStationID());
			}else{  //jv
				map.put("userType",  userT.getIsType());
				map.put("companyID",  ""+userT.getCompanyId());
			}

			/**
			 * 查询必须课   查询type:课程类型，0选修，1必须，2所有
			 */
			if (StringUtils.isNotBlank(MapUtils.getString(map,"courseLabelsList"))) {
				List<String> list = Arrays.stream(MapUtils.getString(map,"courseLabelsList").split(","))
						.collect(Collectors.toList());
				map.put("courseLabelsList",list);
			}else {
				map.remove("courseLabelsList");
			}
			if (StringUtils.isNotBlank(MapUtils.getString(map,"learnType"))) {
				List<String> list = Arrays.stream(MapUtils.getString(map,"learnType").split(","))
						.collect(Collectors.toList());
				map.put("learnType",list);
			}else {
				map.remove("learnType");
			}
			String joinedEndTime = MapUtils.getString(map, "joinedEndTime");
			if (StringUtils.isNotBlank(joinedEndTime)) {
				map.put("joinedEndTime",Date_Util.addDay(joinedEndTime,1));
			}
			if(StringUtils.isNotBlank(MapUtils.getString(map,"courseType"))){
				String courseType = ""+map.get("courseType");
				String[] split = courseType.split(",");
				java.util.ArrayList<Long> stringList = new ArrayList<>(split.length);
				if (split!=null && split.length>0) {
					for (String s : split) {
						if (StringUtils.isNotBlank(s)) {
							stringList.add(Long.valueOf(s));
						}
					}
					map.put("courseType", stringList);
				}

			}else {
				map.remove("courseType");
			}
			if(StringUtils.isNotBlank(MapUtils.getString(map,"engineSystem"))){
				String engineSystem = ""+map.get("engineSystem");
				String[] split = engineSystem.split(",");
				ArrayList<String> stringList = new ArrayList<>(split.length);
				Collections.addAll(stringList,split);
				map.put("engineSystem", stringList);
			}else {
				map.remove("engineSystem");
			}
			log.error("TTTTT:"+map.toString());
			List<CourseTrainingT> courseTrainingList = null;
			if(type.equals("2") || type.equals("1")){
				map.put("flag", 1);
				PageHelper.startPage(page, pagesize);
				courseTrainingList = courseTrainingDao.findCourseTrainingByUser(map);

			}
			/**
			 * 查询选修课
			 */

			List<CourseTrainingT> courseTrainingListXx = null;
			if(type.equals("0")){
				map.put("flag", 0);
				PageHelper.startPage(page, pagesize);
				courseTrainingListXx = courseTrainingDao.findCourseTrainingByUser(map);
			}

			/**
			 * 2、从redis里面获取个人学习进度
			 * 如果redis没有去获取学习进度日志，放入redis中
			 */
			Map<String, CourseStudyT> courseStudyMap = getCourseStudyRedis(userT, map);

			/**
			 * 3、将字典项内容返回给用户
			 */
			int passScore = Integer.valueOf(this.propertiesUtils.getPropertiesValue("passScore"));
			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			//查询必须课----flag	课件类型：0选修，1必须
			if(courseTrainingList != null){
				for(CourseTrainingT courseTrainingT : courseTrainingList){
					if(courseTrainingT == null){//联合查询可能为空
						continue;
					}
//					"id": "DESSED",
//					"courseTitle": "课件名称",
//					"description": "课件描述",
//					"isLogo":1,
//					"showImg": "http://ww.s.g/a.jpg",
//					"flag": "1",
//					"speed ": "学习进度",
//					"systime": "加入时间"
					content = new JSONObject();
					content.put("id", AESTool.encryptString(""+courseTrainingT.getId()));
					content.put("courseTitle", courseTrainingT.getCoursetitle());
					content.put("description", courseTrainingT.getDescription());
					content.put("isLogo", courseTrainingT.getIslogo());
					content.put("showImg", courseTrainingT.getShowimg());
					content.put("flag", 1);


					CourseStudyT studyT = courseStudyMap.get(""+courseTrainingT.getId());
					double speed = 0;
					if(studyT != null){
						if(studyT.getScores()>=passScore){
							speed = 100;
						}else{
							if(studyT.getCoursTime().doubleValue() != 0){
								speed = studyT.getStudytime()/studyT.getCoursTime();
								if(courseTrainingT.getQuestionfilename() == null || courseTrainingT.getQuestionfilename().trim().equals("")){
									speed = speed>1 ? 100 : speed*100;
								}else{
									speed = speed>1 ? 90 : speed*90;
								}
							}
						}
						content.put("systime", PublicTool.dateTimeChangeChina(courseTrainingT.getSystime().substring(0,19)));
					}else{
						content.put("systime", PublicTool.dateTimeChangeChina(courseTrainingT.getSystime().substring(0,19)));
					}
					content.put("speed", speed);
					jsonArray.put(content);
				}
			}
			//查询选修课--flag	课件类型：0选修，1必须
			if(courseTrainingListXx != null){
				for(CourseTrainingT courseTrainingT : courseTrainingListXx){
					if(courseTrainingT == null){
						continue;
					}
					content = new JSONObject();
					content.put("id", AESTool.encryptString(""+courseTrainingT.getId()));
					content.put("courseTitle", courseTrainingT.getCoursetitle());
					content.put("description", courseTrainingT.getDescription());
					content.put("isLogo", courseTrainingT.getIslogo());
					content.put("showImg", courseTrainingT.getShowimg());
					content.put("flag", 0);

					CourseStudyT studyT = courseStudyMap.get(""+courseTrainingT.getId());
					double speed = 0;
					if(studyT != null){
						if(studyT.getScores() >= passScore){
							speed = 100;
						}else{
							if(studyT.getCoursTime().doubleValue() != 0){
								speed = studyT.getStudytime()/studyT.getCoursTime();
								if(courseTrainingT.getQuestionfilename() == null || courseTrainingT.getQuestionfilename().trim().equals("")){
									speed = speed>1 ? 100 : speed*100;
								}else{
									speed = speed>1 ? 90 : speed*90;
								}
							}
						}
						content.put("systime", PublicTool.dateTimeChangeChina(courseTrainingT.getSystime().substring(0,19)));
					}else{
						content.put("systime", PublicTool.dateTimeChangeChina(courseTrainingT.getSystime().substring(0,19)));
					}
					content.put("speed", speed);
					jsonArray.put(content);
				}
			}
			obj.put("courseTrainings", jsonArray);

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		return null;
	}

	/**
	 * App获取学习营课程接口
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getCourseTraining(Map map) {
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询type:课程类型，0热门课程，1最新课程，2考试题库
			 */
			if(map.get("type") == null  || map.get("type").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String type = ""+map.get("type");

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("userId", userT.getId());
			/**
			 * 1 康明斯,2康明斯分公司,3 JV,4 OEM,5 SSOEM,6 Dealer,0	Engine Customer
			 * 康明斯查询所有课件+级别
			 * 客户查询类型所有课件+级别
			 * jv查询自己上传课件 + 级别
			 * dealer则查询企业授权服务站的课件 + 级别
			 */
			if(userT.getIsType() ==0 || userT.getIsType() ==1){
				map.put("userType", 0);
				map.put("dealerLevel",  ""+userT.getDealerLevel());
			}else if(userT.getIsType() ==6){ //dealer用户组
				map.put("userType", 6);
				map.put("dealerLevel",  ""+userT.getDealerLevel());
				map.put("serviceStationID", ""+userT.getServiceStationID());
			}else{
				map.put("userType",  userT.getIsType());
				map.put("dealerLevel",  ""+userT.getDealerLevel());
				map.put("companyID",  ""+userT.getCompanyId());
			}
			/**
			 * 考题不区分级别，普通用户没有考题
			 * 考题只针对dealer、康明斯等，针对dealer删除级别
			 */
			if(type.equals("2")){
				if(userT.getIsType() ==0){
					map.put("dealerLevel","-1");
				}else{
					map.remove("dealerLevel");
				}
			}
			if (StringUtils.isNotBlank(MapUtils.getString(map,"courseLabelsList"))) {
				List<String> list = Arrays.stream(MapUtils.getString(map,"courseLabelsList").split(","))
						.collect(Collectors.toList());
				map.put("courseLabelsList", list);
			}else{
				map.remove("courseLabelsList");
			}
			if (StringUtils.isNotBlank(MapUtils.getString(map,"learnType"))) {
				List<String> list = Arrays.stream(MapUtils.getString(map,"learnType").split(","))
						.collect(Collectors.toList());
				map.put("learnType",list);
			}else{
				map.remove("learnType");
			}
			if(StringUtils.isNotBlank(MapUtils.getString(map,"courseType"))){
				String courseType = ""+map.get("courseType");
				String[] split = courseType.split(",");
				java.util.ArrayList<Long> stringList = new ArrayList<>(split.length);
				if (split!=null && split.length>0) {
					for (String s : split) {
						if (StringUtils.isNotBlank(s)) {
							stringList.add(Long.valueOf(s));
						}
					}
					map.put("courseType", stringList);
				}
			}else {
				map.remove("courseType");
			}
			if(StringUtils.isNotBlank(MapUtils.getString(map,"engineSystem"))){
				String engineSystem = ""+map.get("engineSystem");
				String[] split = engineSystem.split(",");
				ArrayList<String> stringList = new ArrayList<>(split.length);
				Collections.addAll(stringList,split);
				map.put("engineSystem", stringList);
			}else {
				map.remove("engineSystem");
			}
			/**
			 * 搜索课程内容
			 */
			String joinedEndTime = MapUtils.getString(map, "joinedEndTime");
			if (StringUtils.isNotBlank(joinedEndTime)) {
				map.put("joinedEndTime",Date_Util.addDay(joinedEndTime,1));
			}
			log.error("测试 get "+map.toString());
			PageHelper.startPage(page, pagesize);
			Integer sortType = MapUtils.getInteger(map, "sortType");

			if (StringUtils.isNotBlank(type)) {
				if ("0".equals(type)) {
					if (null!=sortType) {
						if (sortType==3 && MapUtils.getInteger(map, "sortingType")==1) {
							PageHelper.orderBy(" a.playbackVolume asc");
						}
						if (sortType==3 && MapUtils.getInteger(map, "sortingType")==2) {
							PageHelper.orderBy("  a.playbackVolume desc");
						}
						if (sortType==1 ) {
							PageHelper.orderBy(" a.isStick desc, case when a.isStick=1 then a.updateTime end desc, case when a.isStick=0 then a.TolNum end desc");
						}
						if (sortType==4 && MapUtils.getInteger(map, "sortingType")==1) {
							PageHelper.orderBy("  a.Systime asc");
						}
						if (sortType==4 && MapUtils.getInteger(map, "sortingType")==2) {
							PageHelper.orderBy("  a.Systime desc");
						}
					}else {
						PageHelper.orderBy(" a.isStick desc, case when a.isStick=1 then a.updateTime end desc, case when a.isStick=0 then a.TolNum end desc");
					}
				}
				if ("2".equals(type) || "1".equals(type) ) {
					if (null!=sortType) {
						if (sortType==3 && MapUtils.getInteger(map, "sortingType")==1) {
							PageHelper.orderBy(" a.playbackVolume asc");
						}
						if (sortType==3 && MapUtils.getInteger(map, "sortingType")==2) {
							PageHelper.orderBy("  a.playbackVolume desc");
						}
						if (sortType==1 ) {
							PageHelper.orderBy(" a.TolNum desc");
						}
						if (sortType==4 && MapUtils.getInteger(map, "sortingType")==1) {
							PageHelper.orderBy("  a.Systime asc");
						}
						if (sortType==4 && MapUtils.getInteger(map, "sortingType")==2) {
							PageHelper.orderBy("  a.Systime desc");
						}
					}else {
						PageHelper.orderBy(" a.Systime desc");
					}
				}
			}

			List<CourseTrainingT> courseTrainingList = courseTrainingDao.findCourseTraining(map);
			/**
			 * 查询用户是否必修
			 */
			Map<String, CourseHasUserT> courseHasUserMap = getCourseHasUserRedis(userT,map);
			/**
			 * 2、从redis里面获取个人学习进度,0热门课程，1最新课程，2考试题库
			 * 如果redis没有去获取学习进度日志，放入redis中
			 */
			Map<String, CourseStudyT> courseStudyMap = null;
			Map<String, CourseExamT> courseExamMap = null;
			if(!type.equals("2")){
				courseStudyMap = getCourseStudyRedis(userT,map);
			}else{
				courseExamMap = getCourseExamRedis(userT,map);
			}
			/**
			 * 3、将内容返回给用户
			 */
			int passScore = Integer.valueOf(this.propertiesUtils.getPropertiesValue("passScore"));
			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			//查询必须课
			if(courseTrainingList != null){
				for(CourseTrainingT courseTrainingT : courseTrainingList){
//					"id": "DESSED",
//					"courseTitle": "课件名称",
//					"description": "课件描述",
//					"type":0,
//					"isLogo":1,
//					"showImg": "http://ww.s.g/a.jpg",
//					"tolNum": "学习次数",
//					"status": "已参加",
//					"studyTime": 0.2,
//					"systime": "发布时间"
					if(courseTrainingT == null){
						continue;
					}
					content = new JSONObject();
					content.put("id", AESTool.encryptString(""+courseTrainingT.getId()));
					content.put("courseTitle", courseTrainingT.getCoursetitle());
					content.put("description", courseTrainingT.getDescription());
					content.put("type", courseTrainingT.getType());
					content.put("isLogo", courseTrainingT.getIslogo());
					content.put("showImg", courseTrainingT.getShowimg());
					content.put("tolNum", courseTrainingT.getTolnum());
					content.put("systime", PublicTool.dateTimeChangeChina(courseTrainingT.getSystime().substring(0,19)));
					/**
					 * 查询必修课，如果选修课指定用户也是必选
					 */
					if(courseTrainingT.getIsmust().intValue() ==1 || courseHasUserMap.get(""+courseTrainingT.getId()) != null){
						content.put("isMust", 1);
					}else{
						content.put("isMust", 0);
					}

					/**
					 * type	课程类型，0热门课程，1最新课程，2考试题库
					 * 如果是考题大比拼，查询客户的考试记录
					 */
					if(!type.equals("2")){
						CourseStudyT studyT = courseStudyMap.get(""+courseTrainingT.getId());
						//status学习状态：0我要学习,1已加入，2已完成
						if(studyT == null){
							content.put("status", 0);
							content.put("studyTime", 0);
							/**
							 * 查询课件是否为必学,如果必修则为已加入,如果选修课指定用户也是必选
							 */
							if(courseTrainingT.getIsmust().intValue() ==1 || courseHasUserMap.get(""+courseTrainingT.getId()) != null){
								content.put("status", 1);
							}
							content.put("scores", 0);
						}else{
							if(studyT.getScores() >= passScore){
								content.put("status", 2);//2已完成
							}else{
								content.put("status", 1);  //1已加入
							}
							content.put("scores", studyT.getScores());
							content.put("studyTime", studyT.getStudytime());
						}
					}else{
						CourseExamT courseExamT = courseExamMap.get(""+courseTrainingT.getId());
						//考试状态：0参加考试，1已考试，2未通过
						if(courseExamT == null){
							content.put("status", 0);
							content.put("scores", 0);
							content.put("studyTime", 0);
						}else{
							if(courseExamT.getScores()> passScore){
								content.put("status", 1);//已考试
							}else{
								content.put("status", 2);  //未通过
							}
							content.put("scores", courseExamT.getScores());
							content.put("studyTime", 0);
						}
					}

					jsonArray.put(content);
				}
			}
			obj.put("courseTrainings", jsonArray);

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		return null;
	}

	/**
	 * App搜索课程接口
	 * @param serviceStationID
	 * @return
	 */
	@Override
	public ModelAndView searchCourseTraining(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询searchTxt
			 */
			String searchTxt = ""+map.get("searchTxt");
			if(map.get("searchTxt") != null  &&  !map.get("searchTxt").toString().equals("")){
				map.put("searchTxt", "%"+searchTxt+"%");
			}
			if(StringUtils.isNotBlank(MapUtils.getString(map,"courseType"))){
				String courseType = ""+map.get("courseType");
				String[] split = courseType.split(",");
				java.util.ArrayList<Long> stringList = new ArrayList<>(split.length);
				if (split!=null && split.length>0) {
					for (String s : split) {
						if (StringUtils.isNotBlank(s)) {
							stringList.add(Long.valueOf(s));
						}
					}
					map.put("courseType", stringList);
				}
			}else {
				map.remove("courseType");
			}
			if(StringUtils.isNotBlank(MapUtils.getString(map,"engineSystem"))){
				String engineSystem = ""+map.get("engineSystem");
				String[] split = engineSystem.split(",");
				ArrayList<String> stringList = new ArrayList<>(split.length);
				Collections.addAll(stringList,split);
				map.put("engineSystem", stringList);
			}else {
				map.remove("engineSystem");
			}


			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("userId", userT.getId());
			/**
			 * 1 康明斯,2康明斯分公司,3 JV,4 OEM,5 SSOEM,6 Dealer,0	Engine Customer
			 * 康明斯查询所有课件+级别
			 * 客户查询类型所有课件+级别
			 * jv查询自己上传课件 + 级别
			 * dealer则查询企业授权服务站的课件 + 级别
			 */
			if(userT.getIsType() ==0 || userT.getIsType() ==1){
				map.put("userType", 0);
				map.put("dealerLevel",  ""+userT.getDealerLevel());
			}else if(userT.getIsType() ==6){ //dealer用户组
				map.put("userType", 6);
				map.put("dealerLevel",  ""+userT.getDealerLevel());
				map.put("serviceStationID", ""+userT.getServiceStationID());
			}else{
				map.put("userType",  userT.getIsType());
				map.put("dealerLevel",  ""+userT.getDealerLevel());
				map.put("companyID",  ""+userT.getCompanyId());
			}

			if(map.get("type") !=null && map.get("type").toString().equals("2")){
				map.remove("dealerLevel");
			}

			if (StringUtils.isNotBlank(MapUtils.getString(map,"courseLabelsList"))) {
				List<String> list = Arrays.stream(MapUtils.getString(map,"courseLabelsList").split(","))
						.collect(Collectors.toList());
				map.put("courseLabelsList", list);
			}else{
				map.remove("courseLabelsList");
			}
			/**
			 * 搜索课程内容
			 */
			PageHelper.startPage(page, pagesize);
			Integer sortType = MapUtils.getInteger(map, "sortType");
			if (null!=sortType) {
				if (sortType==3 && MapUtils.getInteger(map, "sortingType")==1) {
					PageHelper.orderBy(" a.playbackVolume asc");
				}
				if (sortType==3 && MapUtils.getInteger(map, "sortingType")==2) {
					PageHelper.orderBy("  a.playbackVolume desc");
				}
				if (sortType==1 ) {
					PageHelper.orderBy(" a.TolNum desc");
				}
				if (sortType==4 && MapUtils.getInteger(map, "sortingType")==1) {
					PageHelper.orderBy("  a.Systime asc");
				}
				if (sortType==4 && MapUtils.getInteger(map, "sortingType")==2) {
					PageHelper.orderBy("  a.Systime desc");
				}
			}
			log.error("测试 ser "+map.toString());
			List<CourseTrainingT> courseTrainingList = courseTrainingDao.findCourseTraining(map);

			/**
			 * 2、从redis里面获取个人学习进度
			 * 如果redis没有去获取学习进度日志，放入redis中
			 */
			Map<String, CourseStudyT> courseStudyMap = getCourseStudyRedis(userT,map);
			Map<String, CourseExamT> courseExamMap = getCourseExamRedis(userT, map);
			/**
			 * 3、将内容返回给用户
			 */
			int passScore = Integer.valueOf(this.propertiesUtils.getPropertiesValue("passScore"));
			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			//查询必须课
			if(courseTrainingList != null){
				for(CourseTrainingT courseTrainingT : courseTrainingList){
//					"id": "DESSED",
//					"courseTitle": "课件名称",
//					"description": "课件描述",
//					"type":0,
//					"showImg": "http://ww.s.g/a.jpg",
//					"tolNum": "学习次数",
//					"status": "已参加",
//					"studyTime": 0.2,
//					"systime": "发布时间"
					if(courseTrainingT == null){
						continue;
					}
					content = new JSONObject();
					content.put("id", AESTool.encryptString(""+courseTrainingT.getId()));
					content.put("courseTitle", courseTrainingT.getCoursetitle());
					content.put("description", courseTrainingT.getDescription());
					content.put("type", courseTrainingT.getType());
					content.put("showImg", courseTrainingT.getShowimg());
					content.put("isMust", courseTrainingT.getIsmust());
					content.put("tolNum", courseTrainingT.getTolnum());
					content.put("systime", PublicTool.dateTimeChangeChina(courseTrainingT.getSystime().substring(0,19)));

					if(courseTrainingT.getType() == 0) {
						CourseStudyT studyT = courseStudyMap.get(""+courseTrainingT.getId());
						//status学习状态：0我要学习,1已加入，2已完成
						if(studyT == null){
							content.put("status", 0);
							content.put("studyTime", 0);
							/**
							 * 查询课件是否为必学,如果必修则为已加入
							 */
							if(courseTrainingT.getIsmust().intValue() ==1){
								content.put("status", 1);
							}
							content.put("scores", 0);
						}else{
							if(studyT.getScores() >= passScore){
								content.put("status", 2);//2已完成
							}else{
								content.put("status", 1);  //1已加入
							}
							content.put("scores", studyT.getScores());
							content.put("studyTime", studyT.getStudytime());
						}
					} else {
						CourseExamT examT = courseExamMap.get(""+courseTrainingT.getId());
						//status学习状态：0未参加,1已通过，2未通过
						if(examT == null){
							content.put("status", 0);
							content.put("studyTime", 0);
							content.put("scores", 0);
						}else{
							if(examT.getScores()> passScore){
								content.put("status", 1);//1已通过
							}else{
								content.put("status", 2);  //2未通过
							}
							content.put("scores", examT.getScores());
							content.put("studyTime", 0);
						}
					}

					jsonArray.put(content);
				}
			}
			obj.put("courseTrainings", jsonArray);

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * App获取课程详细接口
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getCourseDetail(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询courseTrainingID是否为空
			 */
			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);
			/**
			 * 查询课件内容,获取分数
			 */
			List<CourseTrainingT> courseTrainingList = courseTrainingDao.findCourseTrainingByID(courseTrainingID);
			if(courseTrainingList.size() ==0){
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			CourseTrainingT courseTrainingT = courseTrainingList.get(0);

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("userId", userT.getId());
			/**
			 * 2、从redis里面获取个人课程详细进度
			 */
			Map<String, CourseStudyDetailT> courseStudyDetailMap = getCourseStudyDetailRedis(userT,map);
			/**
			 * 3、获取课程详细
			 */
			List<CourseDetailT> courseDetailTList = courseTrainingDao.findCourseDetailById(courseTrainingID);
			//获取课程考试日志
			List<CourseExamT> CourseExamList = courseTrainingDao.findCourseExamByUserId(map);
			/**
			 * 4、将内容返回给用户
			 */
			obj.put("status", 0);
			obj.put("msg", "");
			if(courseTrainingT.getQuestionfilename()== null || courseTrainingT.getQuestionfilename().trim().equals("")){
				obj.put("isExam", "0");
			}else{
				obj.put("isExam", "1");
			}
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			/**
			 * 查询课程详细
			 */
			for(CourseDetailT courseDetailT : courseDetailTList){
//				"id": "DESSED",
//				"detailTitle": "课件名称",
//				"videoUrl": "http://ww.s.g/a.avi",
//				"videoTime": 0.2,
//				"fileUrl": "http://ww.s.g/a.pdf",
//				"type": 0
				content = new JSONObject();
				content.put("id", AESTool.encryptString(""+courseDetailT.getId()));
				content.put("detailTitle", courseDetailT.getDetailtitle());
				content.put("videoUrl", courseDetailT.getVideourl());
				content.put("videoTime", (courseDetailT.getVideotime()/60));//最开始单位为小时，现修改为分钟-2018-04-13
				content.put("fileUrl", courseDetailT.getFileurl());
				/**
				 * 查询用户是否已经学习
				 */
				if(courseStudyDetailMap.get(""+courseDetailT.getId()) == null){
					content.put("type", 0);
				}else{
					content.put("type", 1);
				}
				jsonArray.put(content);
			}
			obj.put("courseDetails", jsonArray);
			/**
			 * 获取课程考试日志
			 */
			jsonArray = new JSONArray();
			for(CourseExamT courseExamT : CourseExamList){
//				"id": "DESSED",
//				"scores": "80"
//				"isPass":0  //是否通过，0未合格，1合格
				content = new JSONObject();
				content.put("id", AESTool.encryptString(""+courseExamT.getId()));
				content.put("scores", courseExamT.getScores());
				content.put("isPass", courseExamT.getFlag());
				jsonArray.put(content);
			}
			obj.put("courseExams", jsonArray);

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * App上传学习课程接口
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView uploadCourseDetail(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询courseTrainingID是否为空
			 */
			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);
			//课程详细表ID，AES加密
			if(map.get("courseDetailID") == null  || map.get("courseDetailID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseDetailID = ""+map.get("courseDetailID");
			courseDetailID =  AESTool.decryptString(courseDetailID);
			map.put("courseDetailID", courseDetailID);
			//学习时长
			if(map.get("studyTime") == null  || map.get("studyTime").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			//学习结束时间
			if(map.get("endTime") == null  || map.get("endTime").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String endTime = ""+map.get("endTime");
			map.put("endTime", PublicTool.dateTimeChangeUs(endTime));

			//0正常，1学习完成
			if(map.get("flag") == null  || map.get("flag").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			//学习开始时间
			if(map.get("systime") == null  || map.get("systime").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String systime = ""+map.get("systime");
			map.put("systime", PublicTool.dateTimeChangeUs(systime));

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("serviceStationId", userT.getServiceStationID());
			map.put("userId", userT.getId());

			/**
			 * 2、 从redis获取个人学习日志，如果redis没有则去获取学习进度日志，放入redis中 
			 * 如果没有本课程学习日志，则插入学习日志，如果存在则修改学习时长
			 */
//			redisClientUtils.delkey("courseStudyMap"+userT.getId());
			Map<String, CourseStudyT> courseStudyMap = getCourseStudyRedis(userT,map);
			CourseStudyT  bean = courseStudyMap.get(courseTrainingID);
			/**
			 * 查询课件学习时长
			 */
			double coursTime = 0;
			List<CourseDetailT> courseDetailTList = courseTrainingDao.findCourseDetailStudyTimeById(courseTrainingID);
			if(courseDetailTList.size()>0){
				coursTime = courseDetailTList.get(0).getVideotime()/60d;//vedio原来是小时，现在是分钟
			}
			map.put("coursTime", coursTime);


			float studyTime = Float.valueOf(""+map.get("studyTime"));//SVN学习时间
			/**
			 * 3、插入课程学习日志
			 */
			if(bean == null){
				/**
				 * flag：0正常，1学习完成
				 * 如果flag=0则学习未完成， 更改用户的学习时间为0
				 */
				if(map.get("flag").toString().equals("0")){
					map.put("studyTime", 0);
				}
				courseTrainingDao.insertCourseStudy(map);//插入课程学习日志
				log.warn("插入      用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录");
				//重新将课程详细日志学习时间放入map
				map.put("studyTime", studyTime);
				map.put("courseStudyID", map.get("id"));
			}else{
				map.put("courseStudyID", bean.getId());
				/**
				 * flag：0正常，1学习完成
				 * 如果flag=1则学习完成， 修改用户的学习时间
				 */
				if(map.get("flag").toString().equals("1")){
					map.put("studyTime", bean.getStudytime() + studyTime);
					courseTrainingDao.updateCourseStudy(map); //修改个人课程学习日志
				}
				//重新将课程详细日志学习时间放入map
				map.put("studyTime", studyTime);
			}
			/**
			 * 清除redis中courseStudyMap，重新插入redis
			 */
			redisClientUtils.delkey("courseStudyMap"+userT.getId());
			log.warn("用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录被删除");
			redisClientUtils.delkey("courseStudyDetailMap"+userT.getId());
			/**
			 * 5、插入课程学习详细日志
			 */
			int result = courseTrainingDao.insertCourseStudyDetail(map);
			log.warn("插入      用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录");
			/**
			 * 6、将内容返回给用户
			 */
			obj.put("status", 0);
			obj.put("msg", "");

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * App获取课程考试接口
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getCourseExam(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询courseTrainingID是否为空
			 */
			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);

			//课程类型：0课件，1考试大比拼
			if(map.get("type") == null  || map.get("type").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String type = ""+map.get("type");

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("userId", userT.getId());
			/**
			 * 2、查询考题
			 */
			/**
			 * 查询第几次考试
			 */
			int questionNum = 1;
			//课程类型：0课件，1考试大比拼
			if(type.equals("0")){
				List<CourseExamT> courseExamList = courseTrainingDao.findCourseExamByUserId(map);
				questionNum = courseExamList.size()+1;
			}else{
				map.put("type", 1);//课件类型：0课件，1考试大比拼
				/**
				 * 添加考试次数
				 */
				courseTrainingDao.updateCourseTrainingTol(courseTrainingID);
			}

			/**
			 * 查询课件内容
			 */
			List<CourseTrainingT> courseTrainingList = courseTrainingDao.findCourseTrainingByID(courseTrainingID);
			if(courseTrainingList.size() ==0){
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			CourseTrainingT bean = courseTrainingList.get(0);
			/**
			 * 查询考题
			 */
			PageHelper.startPage(1, bean.getQuestionnum());
			List<CourseQuestionT> CourseQuestionList = courseTrainingDao.findCourseQuestionById(map);


			/**
			 * 3、将内容返回给用户
			 */
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("questionNum", questionNum);
			obj.put("questionTime", (bean.getQuestiontime()/60));//最开始单位为小时，现修改为分钟-2018-04-13
			obj.put("questionTol", bean.getQuestionnum());
			obj.put("scoresEvery", bean.getScoresevery());
			//考试合格分数
			int passScore = Integer.valueOf(this.propertiesUtils.getPropertiesValue("passScore"));
			obj.put("passScore", passScore);

			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			/**
			 * 查询课程详细
			 */
			for(CourseQuestionT cqBean : CourseQuestionList){
//				"id": "DESSED",
//				"questionTitle": "考题标题",
//				"questionType": 0,
//				"questionContent": "考题选项",
//				"rightAnswer": "a"
				content = new JSONObject();
				content.put("id", AESTool.encryptString(""+cqBean.getId()));
				content.put("questionTitle", cqBean.getQuestiontitle());
				content.put("questionType", cqBean.getQuestiontype());
				content.put("questionContent", cqBean.getQuestioncontent());
				content.put("rightAnswer", cqBean.getRightanswer());
				jsonArray.put(content);
			}
			obj.put("questionDetails", jsonArray);

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * App上传考试课题详细接口 
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView uploadCourseExam(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询courseTrainingID是否为空
			 */
			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);

			//开始时间
			if(map.get("startTime") == null  || map.get("startTime").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String startTime = ""+map.get("startTime");
			map.put("startTime", PublicTool.dateTimeChangeUs(startTime));

			//结束时间
			if(map.get("endTime") == null  || map.get("endTime").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String endTime = ""+map.get("endTime");
			map.put("endTime", PublicTool.dateTimeChangeUs(endTime));

			//考试分数
			if(map.get("scores") == null  || map.get("scores").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			//考试详情
			if(map.get("questionDetail") == null  || map.get("questionDetail").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}


			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("serviceStationID", userT.getServiceStationID());
			map.put("userId", userT.getId());
			/**
			 * 判断用户的考试分数是否通过
			 */
			int passScore = Integer.valueOf(this.propertiesUtils.getPropertiesValue("passScore"));
			if(Integer.valueOf(map.get("scores").toString()).intValue() >=passScore){
				map.put("flag", 1);
			}else{
				map.put("flag", 0);
			}
			/**
			 * 2、 插入课程考试日志
			 */
			int result = courseTrainingDao.insertCourseExam(map);
			if(result<1){
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
			}
			/**
			 * 获取考试插入的ID
			 */
			String courseExamID  = ""+map.get("id");
			/**
			 * 插入考试详情
			 */
			JSONArray jsonArray = new JSONArray(map.get("questionDetail").toString());
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			for(int i=0; i<jsonArray.length(); i++){

				JSONObject json = jsonArray.getJSONObject(i);
				Map<String, Object> cxMap = new HashMap<String,Object>();
				cxMap.put("courseExamID", courseExamID);
				cxMap.put("courseQuestionID", AESTool.decryptString(""+json.get("id")));
				cxMap.put("userId", userT.getId());
				cxMap.put("answer", json.get("answer"));
				cxMap.put("scores", json.get("scores"));
				list.add(cxMap);
			}
			result = courseTrainingDao.insertCourseExamDetail(list);

			/**
			 * 3、 从redis获取个人学习日志，更新学习考试分数
			 */
			Map<String, CourseStudyT> courseStudyMap = getCourseStudyRedis(userT,map);
			CourseStudyT  bean = courseStudyMap.get(courseTrainingID);
			/**
			 * 学习大比拼没有学习记录
			 */
			if(bean != null){
				map.put("studyTime", bean.getStudytime());
				map.put("coursTime", bean.getCoursTime());
				map.put("courseStudyID", bean.getId());
				courseTrainingDao.updateCourseStudy(map);
			}

			/**
			 * 删除redis个人课程学习日志的分数
			 * 删除redis中考试记录
			 */
			redisClientUtils.delkey("courseStudyMap"+userT.getId());
			log.warn("用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录被删除");
			redisClientUtils.delkey("courseExamMap"+userT.getId());
			/**
			 * 4、将内容返回给用户
			 */
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("courseExamID", AESTool.encryptString(courseExamID));

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * App查询课程考试结果接口 
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getCourseExamDetail(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			//HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询courseTrainingID是否为空
			 */
			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);
			/**
			 * 首先查询courseExamID是否为空
			 */
			if(map.get("courseExamID") == null  || map.get("courseExamID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseExamID = ""+map.get("courseExamID");
			courseExamID =  AESTool.decryptString(courseExamID);
			/**
			 * 查询课件内容,获取分数
			 */
			List<CourseTrainingT> courseTrainingList = courseTrainingDao.findCourseTrainingByID(courseTrainingID);
			if(courseTrainingList.size() ==0){
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			CourseTrainingT courseTrainingT = courseTrainingList.get(0);
			/**
			 * 2、查询考题的详细结果
			 */
			List<CourseQuestionT> ourseQuestionTList = courseTrainingDao.findCourseExamDetailById(courseExamID);
			/**
			 * 3、将内容返回给用户
			 */
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("scoresEvery", courseTrainingT.getScoresevery());
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			/**
			 * 查询课程详细
			 */
			for(CourseQuestionT bean : ourseQuestionTList){
//				"id": "DESSED",
//				"questionTitle": "考题标题",
//				"questionType": 0,
//				"questionContent": "考题选项",
//				"rightAnswer": "a",
//				"answer": "b"
				content = new JSONObject();
				content.put("id", AESTool.encryptString(""+bean.getId()));
				content.put("questionTitle", bean.getQuestiontitle());
				content.put("questionType", bean.getQuestiontype());
				content.put("questionContent", bean.getQuestioncontent());
				content.put("rightAnswer", bean.getRightanswer());
				content.put("answer", bean.getAnswer());
				content.put("scores", bean.getScores());
				jsonArray.put(content);
			}
			obj.put("questionDetails", jsonArray);

			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * App用户修改课件状态接口 
	 * @param map
	 * @return
	 */
	public ModelAndView updateCourseTraining(Map map){
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();
			/**
			 * 1、首先查询courseTrainingID是否为空
			 */
			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);
			/**
			 * 首先查询flag是否为空
			 */
			if(map.get("flag") == null  || map.get("flag").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("userId", userT.getId());

			/**
			 * 2、更改考试状态
			 * flag	课件状态：0加入课件，-1删除课件
			 */
			if(map.get("flag").toString().equals("0")){
				/**
				 * 3、 从redis获取个人学习日志，如果redis没有则去获取学习进度日志，放入redis中 
				 * 如果没有本课程学习日志，则插入学习日志，如果存在则修改学习时长
				 */
				Map<String, CourseStudyT> courseStudyMap = getCourseStudyRedis(userT,map);
				CourseStudyT  bean = courseStudyMap.get(courseTrainingID);
				if(bean == null){
					map.put("serviceStationId", userT.getServiceStationID());
					/**
					 * 查询课件学习时长
					 */
					double coursTime = 0;
					List<CourseDetailT> courseDetailTList = courseTrainingDao.findCourseDetailStudyTimeById(courseTrainingID);
					if(courseDetailTList.size()>0){
						coursTime = courseDetailTList.get(0)== null ? 0 : courseDetailTList.get(0).getVideotime();
					}
					map.put("coursTime", coursTime);
					map.put("studyTime", 0);
					map.put("systime", PublicTool.dateTimeChangeUs(PublicTool.getNowTime()));

					courseTrainingDao.insertCourseStudy(map);//插入课程学习日志
					log.warn("插入      用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录");
					courseTrainingDao.updateCourseTrainingTol(courseTrainingID); //添加课程学习的总数量
				}
				obj.put("status", 0);
				obj.put("msg", "");
				/**
				 * 清楚redis的学习日志
				 */
				redisClientUtils.delkey("courseStudyMap"+userT.getId());
				log.warn("用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录被删除");
				/**
				 * 插入选修课关联日志表
				 */
				map.put("flag", 0);
				courseTrainingDao.insertCourseHasUser(map);
			}else if(map.get("flag").toString().equals("-1")){
				//修改个人学习详细日志状态,必须先清空个人学习详细日志,因为联表查询
				courseTrainingDao.updateCourseStudyDetailStatus(map);
				//修改个人学习日志状态
				int result = courseTrainingDao.updateCourseStudyStatus(map);
				//修改课程考试日志状态
				courseTrainingDao.updateCourseExamStatus(map);
				obj.put("status", 0);
				obj.put("msg", "");

				/**
				 * 清楚redis的学习日志
				 */
				redisClientUtils.delkey("courseStudyMap"+userT.getId());
				log.warn("用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录被删除");
				redisClientUtils.delkey("courseStudyDetailMap"+userT.getId());
				redisClientUtils.delkey("courseExamMap"+userT.getId());
				/**
				 * 清除选修客户关联日志表
				 */
				courseTrainingDao.updateCourseHasUser(map);
			}else if(map.get("flag").toString().equals("-2")){

				//修改个人学习详细日志状态,必须先清空个人学习详细日志,因为联表查询
				courseTrainingDao.updateCourseStudyDetailStatus(map);
				//修改个人学习日志状态
				int result = courseTrainingDao.updateCourseStudyStatus(map);
				//修改课程考试日志状态
				courseTrainingDao.updateCourseExamStatus(map);
				obj.put("status", 0);
				obj.put("msg", "");

				/**
				 * 清楚redis的学习日志
				 */
				redisClientUtils.delkey("courseStudyMap"+userT.getId());
				log.warn("用户名：" + userT.getUserName() + ", ID: " + userT.getId() + "的课程学习记录被删除 ");
				redisClientUtils.delkey("courseStudyDetailMap"+userT.getId());
				redisClientUtils.delkey("courseExamMap"+userT.getId());
			}
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * 从redis获取个人学习日志，如果redis没有则去获取学习进度日志，放入redis中
	 * @param userT
	 * @param map
	 * @return
	 */
	private Map<String, CourseStudyT> getCourseStudyRedis(UserT userT,Map map){
		Map<String, CourseStudyT> courseStudyMap = (Map<String, CourseStudyT>)redisClientUtils.getObject("courseStudyMap"+userT.getId());
		if (courseStudyMap == null || courseStudyMap.size() <= 0) {
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			List<CourseStudyT>  courseStudyList = courseTrainingDao.findCourseStudyByUser(map);
			if(courseStudyList != null){
				courseStudyMap = new HashMap<String, CourseStudyT>();
				for(CourseStudyT studyBean : courseStudyList){
					if (courseStudyMap.containsKey(studyBean.getCourseTrainingID().toString())) {
						CourseStudyT courseStudyT = courseStudyMap.get(studyBean.getCourseTrainingID().toString());
						courseStudyT.setStudytime(courseStudyT.getStudytime() + studyBean.getStudytime());
					} else {
						courseStudyMap.put("" + studyBean.getCourseTrainingID(), studyBean);
					}
				}
				//放入redis中									
				redisClientUtils.setObject("courseStudyMap"+userT.getId(), courseStudyMap, redisCacheTime);
			}
		}
		return courseStudyMap;
	}

	/**
	 * 从redis获取个人课程详细学习日志，如果redis没有则去获取个人课程详细学习日志，放入redis中
	 * @param userT
	 * @param courseTrainingID
	 * @return
	 */
	private Map<String, CourseStudyDetailT> getCourseStudyDetailRedis(UserT userT,Map map){
		Map<String, CourseStudyDetailT> courseStudyDetailMap =(Map<String, CourseStudyDetailT>)redisClientUtils.getObject("courseStudyDetailMap"+userT.getId());
		if(courseStudyDetailMap == null){
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			List<CourseStudyDetailT>  courseStudyDetailList = courseTrainingDao.findCourseStudyDetailByUserId(map);
			if(courseStudyDetailList != null){
				courseStudyDetailMap = new HashMap<String, CourseStudyDetailT>();
				for(CourseStudyDetailT studyBean : courseStudyDetailList){
					courseStudyDetailMap.put(""+studyBean.getCoursedetailid(), studyBean);
				}
				//放入redis中									
				redisClientUtils.setObject("courseStudyDetailMap"+userT.getId(), courseStudyDetailMap, redisCacheTime);
			}
		}
		return courseStudyDetailMap;
	}

	/**
	 * 从redis获取个人考试日志，如果redis没有则去获取个人考试日志，放入redis中
	 * @param userT
	 * @param courseTrainingID
	 * @return
	 */
	private Map<String, CourseExamT> getCourseExamRedis(UserT userT,Map map){
		Map<String, CourseExamT> courseExamMap =(Map<String, CourseExamT>)redisClientUtils.getObject("courseExamMap"+userT.getId());
		if(courseExamMap == null || courseExamMap.size()==0){
			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
			List<CourseExamT>  courseExamList = courseTrainingDao.findCourseExamByUserId(map);
			if(courseExamList != null){
				courseExamMap = new HashMap<String, CourseExamT>();
				for(CourseExamT studyBean : courseExamList){
					courseExamMap.put(""+studyBean.getCoursetrainingid(), studyBean);
				}
				//放入redis中									
				redisClientUtils.setObject("courseExamMap"+userT.getId(), courseExamMap, redisCacheTime);
			}
		}
		return courseExamMap;
	}

	/**
	 * 从redis获取个人必修课
	 * @param userT
	 * @param map
	 * @return
	 */
	private Map<String, CourseHasUserT> getCourseHasUserRedis(UserT userT,Map map){
//		Map<String, CourseHasUserT> CourseHasUserMap =(Map<String, CourseHasUserT>)redisClientUtils.getObject("courseHasUserMap"+userT.getId());
//		if(CourseHasUserMap == null){
//			int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
//			List<CourseHasUserT>  courseHasUserList = courseTrainingDao.findCourseHasUserByUserId(map);
//			if(courseHasUserList != null){
//				CourseHasUserMap = new HashMap<String, CourseHasUserT>();
//				for(CourseHasUserT studyBean : courseHasUserList){
//					CourseHasUserMap.put(""+studyBean.getCoursetrainingid(), studyBean);
//				}					
//				//放入redis中									
//				redisClientUtils.setObject("courseHasUserMap"+userT.getId(), CourseHasUserMap, redisCacheTime);
//			}
//		}
		Map<String, CourseHasUserT> CourseHasUserMap = new HashMap<String, CourseHasUserT>();
		List<CourseHasUserT>  courseHasUserList = courseTrainingDao.findCourseHasUserByUserId(map);
		if(courseHasUserList != null){
			for(CourseHasUserT studyBean : courseHasUserList){
				CourseHasUserMap.put(""+studyBean.getCoursetrainingid(), studyBean);
			}
		}
		return CourseHasUserMap;
	}

	/**
	 * 获取课程是否已加入学习
	 * @param map
	 * @return
	 */
	public ModelAndView getCourseStudyStatus(Map map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();

			if(map.get("courseTrainingID") == null  || map.get("courseTrainingID").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			String courseTrainingID = ""+map.get("courseTrainingID");
			courseTrainingID =  AESTool.decryptString(courseTrainingID);
			map.put("courseTrainingID", courseTrainingID);

			/**
			 * 查询用户信息
			 */
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			map.put("userId", userT.getId());
			map.put("dealerLevel", userT.getDealerLevel());
			List<Map<String, Object>> result = courseTrainingDao.getCourseStudyStatus(map);

			if(null == result || result.size() == 0) {
				obj.put("status", -11);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-11));

				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}

			Map<String, Object> reMap = result.get(0);

			reMap.put("id",AESTool.encryptString("" + reMap.get("id")));
			reMap.put("systime",PublicTool.dateTimeChangeChina((reMap.get("systime").toString()).substring(0,19)));

			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("data", reMap);
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}

	/**
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView updatePlaybackVolume(Map<String, Object> map) {
		JSONObject obj = new JSONObject();
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String id = MapUtils.getString(map, "id");
		if (StringUtils.isBlank(id)) {
			obj.put("status", -99);
			obj.put("msg", "请输入id");
			//返回客户
			ParameterTool.writeResponse(response, obj.toString());
			return null;
		}
		String s = AESTool.decryptString(id);
		CourseTrainingT courseTrainingT = courseTrainingDao.findById(Integer.valueOf(s));
		if (courseTrainingT != null) {
			CourseTrainingT trainingT = new CourseTrainingT();
			trainingT.setId(Integer.valueOf(s));
			trainingT.setPlaybackVolume(courseTrainingT.getPlaybackVolume() == null ? 1 : courseTrainingT.getPlaybackVolume() + 1);
			int update = courseTrainingDao.updatePlaybackVolume(trainingT);
			if (update > 0) {
				obj.put("status", 0);
				obj.put("msg", "更新成功");

			} else {
				obj.put("status", -99);
				obj.put("msg", "更新失败");
			}
		} else {
			obj.put("status", -99);
			obj.put("msg", "请输入正确的id");
		}
		//返回客户
		ParameterTool.writeResponse(response, obj.toString());
		return null;
	}
}
